package com.chushouya.product.service.sync.impl;

import com.chushouya.product.dao.entity.BrandEntity;
import com.chushouya.product.dao.entity.CategoryBrandEntity;
import com.chushouya.product.dao.entity.CategoryEntity;
import com.chushouya.product.dao.entity.ProductEntity;
import com.chushouya.product.dao.repository.BrandRepository;
import com.chushouya.product.dao.repository.CategoryBrandRepository;
import com.chushouya.product.dao.repository.CategoryRepository;
import com.chushouya.product.dao.repository.ProductRepository;
import com.chushouya.product.dto.admin.brand.BrandQuery;
import com.chushouya.product.dto.admin.category.CategoryQuery;
import com.chushouya.product.dto.admin.product.query.ProductQuery;
import com.chushouya.product.dto.api.suhuishou.SuhuishouBrandDTO;
import com.chushouya.product.dto.api.suhuishou.SuhuishouProductDTO;
import com.chushouya.product.dto.api.suhuishou.SuhuishouProductListDTO;
import com.chushouya.product.dto.api.suhuishou.SuhuishouProductRowDTO;
import com.chushouya.product.service.api.SuhuishouProductApiService;
import com.chushouya.product.rabbitmq.sender.SuhuishouSyncMessageSender;
import com.chushouya.product.service.sync.SuhuishouSyncService;
import com.general.framework.core.lang.Lists;
import com.general.framework.core.lang.Strings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 速回收同步服务实现类
 * 
 * @author system
 */
@Slf4j
@Service("productSuhuishouSyncService")
public class SuhuishouSyncServiceImpl implements SuhuishouSyncService {

    @Resource
    private SuhuishouProductApiService suhuishouProductApiService;
    
    @Resource
    private BrandRepository brandRepository;
    
    @Resource
    private CategoryBrandRepository categoryBrandRepository;
    
    @Resource
    private CategoryRepository categoryRepository;
    
    @Resource
    private ProductRepository productRepository;
    
    @Resource
    private SuhuishouSyncMessageSender suhuishouSyncMessageSender;
    
    /**
     * 预定义的分类ID列表 - 对应PHP版本的categoryList
     */
    private static final List<Long> CATEGORY_LIST = Arrays.asList(
        100001L, 100002L, 100003L, 100004L, 100005L, 100006L, 100007L, 
        100009L, 100010L, 100011L, 100012L, 100013L, 100014L, 100015L
    );

    @Override
    public void syncBrandList() {
        log.info("开始同步速回收品牌列表");
        
        // 使用消息队列异步处理，避免阻塞主线程
        Long[] categoryIds = CATEGORY_LIST.toArray(new Long[0]);
        suhuishouSyncMessageSender.sendBrandSyncMessageBatch(categoryIds);
        
        log.info("速回收品牌列表同步消息已发送，分类数量: {}", CATEGORY_LIST.size());
    }

    @Override
    public void syncProductList() {
        log.info("开始同步速回收产品列表");
        List<CategoryBrandEntity> brandList = categoryBrandRepository.selectAll();
        
        if (Lists.isEmpty(brandList)) {
            log.warn("没有找到品牌分类关系数据，跳过产品同步");
            return;
        }
        
        // 使用消息队列异步处理，避免阻塞主线程
        for (int i = 0; i < brandList.size(); i++) {
            CategoryBrandEntity categoryBrand = brandList.get(i);
            try {
                // 每个消息间隔一定时间发送，避免API调用过于频繁
                int delaySeconds = i * 5; // 每5秒发送一个
                suhuishouSyncMessageSender.sendProductSyncMessage(
                    categoryBrand.getCategoryId(), 
                    categoryBrand.getBrandId(), 
                    delaySeconds
                );
            } catch (Exception e) {
                log.error("发送产品同步消息失败，分类ID: {}, 品牌ID: {}", 
                        categoryBrand.getCategoryId(), categoryBrand.getBrandId(), e);
            }
        }
        
        log.info("速回收产品列表同步消息已发送，品牌数量: {}", brandList.size());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void syncBrand(Long categoryId) {
        log.info("同步速回收产品品牌ID：{}", categoryId);
        
        // 获取本地氢回收品牌ID列表
        List<Long> qingBrandIdList = getQinghuishouBrandIdList(categoryId);
        
        // 获取速回收品牌列表
        List<SuhuishouBrandDTO> suBrandList = getSuhuishouBrandList(categoryId);
        
        if (Lists.isEmpty(suBrandList)) {
            log.warn("分类{}没有获取到速回收品牌数据", categoryId);
            return;
        }
        
        // 获取速回收品牌ID列表
        List<Long> suBrandIdList = suBrandList.stream()
            .map(SuhuishouBrandDTO::getBrandId)
            .collect(Collectors.toList());
        
        // 找出差异的品牌ID（需要新增的）
        List<Long> diffBrandIdList = suBrandIdList.stream()
            .filter(id -> !qingBrandIdList.contains(id))
            .collect(Collectors.toList());
        
        if (Lists.isEmpty(diffBrandIdList)) {
            log.info("分类{}没有需要同步的新品牌", categoryId);
            return;
        }
        
        log.info("分类{}需要同步{}个新品牌", categoryId, diffBrandIdList.size());
        
        // 批量创建品牌和分类品牌关系
        List<CategoryBrandEntity> categoryBrandList = new ArrayList<>();
        
        for (SuhuishouBrandDTO suBrand : suBrandList) {
            if (diffBrandIdList.contains(suBrand.getBrandId())) {
                // 创建或获取氢回收品牌ID
                Long qingBrandId = getOrCreateQingBrandId(suBrand);
                
                // 创建分类品牌关系
                CategoryBrandEntity categoryBrand = new CategoryBrandEntity();
                categoryBrand.setCategoryId(categoryId);
                categoryBrand.setBrandId(qingBrandId);
                categoryBrand.setSort(50);
                categoryBrand.setHandleUser("system");
                categoryBrand.setCreateTime(new Date());
                categoryBrand.setUpdateTime(new Date());
                
                categoryBrandList.add(categoryBrand);
            }
        }
        
        // 批量插入分类品牌关系
        if (Lists.isNotEmpty(categoryBrandList)) {
            categoryBrandRepository.insertList(categoryBrandList);
            log.info("分类{}成功同步{}个品牌", categoryId, categoryBrandList.size());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void syncProduct(Long categoryId, Long brandId) {
        log.info("同步速回收产品分类ID：{}，品牌ID：{}", categoryId, brandId);
        
        // 获取分类名称和品牌名称
        String categoryName = getCategoryName(categoryId);
        String brandName = getBrandName(brandId);
        
        // 获取本地氢回收产品列表（包含完整信息）
        ProductQuery productQuery = new ProductQuery();
        productQuery.setCategoryId(categoryId);
        productQuery.setBrandId(brandId);
        List<ProductEntity> existingProductList = productRepository.selectList(productQuery);
        
        // 构建速回收产品ID到本地产品的映射
        Map<Long, ProductEntity> suProductIdToProductMap = existingProductList.stream()
            .filter(p -> p.getSuProductId() != null)
            .collect(Collectors.toMap(ProductEntity::getSuProductId, p -> p));
        
        // 获取速回收产品列表
        SuhuishouProductListDTO suProductListDTO = getSuhuishouProductList(categoryId, brandId);
        
        if (suProductListDTO == null || Lists.isEmpty(suProductListDTO.getRows())) {
            log.warn("分类{}品牌{}没有获取到速回收产品数据", categoryId, brandId);
            return;
        }
        
        List<SuhuishouProductRowDTO> suProductList = suProductListDTO.getRows();
        
        // 分别处理新增和更新
        List<ProductEntity> insertList = new ArrayList<>();
        List<ProductEntity> updateList = new ArrayList<>();
        
        for (SuhuishouProductRowDTO suProduct : suProductList) {
            Long suProductId = suProduct.getProductId();
            
            if (suProductIdToProductMap.containsKey(suProductId)) {
                // 产品已存在，更新价格
                ProductEntity existingProduct = suProductIdToProductMap.get(suProductId);
                ProductEntity updateProduct = new ProductEntity();
                updateProduct.setProductId(existingProduct.getProductId());
                updateProduct.setMaxPrice(suProduct.getMaxPrice() != null ? suProduct.getMaxPrice() : BigDecimal.ZERO);
                updateProduct.setUpdateTime(new Date());
                updateList.add(updateProduct);
            } else {
                // 产品不存在，新增
                ProductEntity product = new ProductEntity();
                product.setProductName(suProduct.getProductName());
                product.setProductImage(suProduct.getProductImage());
                product.setKeywords(generateKeywords(suProduct.getProductName()));
                product.setCategoryId(categoryId);
                product.setCategoryName(categoryName);
                product.setBrandId(brandId);
                product.setBrandName(brandName);
                product.setSeriesId(0L);
                product.setSeriesName("");
                product.setSort(50);
                product.setMaxPrice(suProduct.getMaxPrice() != null ? suProduct.getMaxPrice() : BigDecimal.ZERO);
                product.setStatus(1);
                product.setHandleUser("system");
                product.setDelFlag(0);
                product.setSuBrandId(0L);
                product.setSuCategoryId(0L);
                product.setSuProductId(suProduct.getProductId());
                product.setCreateTime(new Date());
                product.setUpdateTime(new Date());
                
                insertList.add(product);
            }
        }
        
        // 批量插入新产品
        if (Lists.isNotEmpty(insertList)) {
            productRepository.insertList(insertList);
            log.info("分类{}品牌{}成功新增{}个产品", categoryId, brandId, insertList.size());
        }
        
        // 批量更新产品价格
        if (Lists.isNotEmpty(updateList)) {
            for (ProductEntity updateProduct : updateList) {
                productRepository.updateByPrimaryKeySelective(updateProduct);
            }
            log.info("分类{}品牌{}成功更新{}个产品价格", categoryId, brandId, updateList.size());
        }
        
        log.info("分类{}品牌{}同步完成，新增: {}，更新: {}", categoryId, brandId, insertList.size(), updateList.size());
    }

    @Override
    public List<Long> getQinghuishouBrandIdList(Long categoryId) {
        // 获取分类下的所有品牌关系
        List<CategoryBrandEntity> categoryBrandList = categoryBrandRepository.selectByCategoryId(categoryId);
        
        if (Lists.isEmpty(categoryBrandList)) {
            return new ArrayList<>();
        }
        
        List<Long> brandIdList = categoryBrandList.stream()
            .map(CategoryBrandEntity::getBrandId)
            .collect(Collectors.toList());
        
        // 获取这些品牌的速回收品牌ID
        BrandQuery brandQuery = new BrandQuery();
        brandQuery.setBrandIdList(brandIdList);
        List<BrandEntity> brandList = brandRepository.selectList(brandQuery);
        
        return brandList.stream()
            .map(BrandEntity::getSuBrandId)
            .filter(Objects::nonNull)
            .collect(Collectors.toList());
    }

    @Override
    public List<SuhuishouBrandDTO> getSuhuishouBrandList(Long categoryId) {
        try {
            return suhuishouProductApiService.requestBrandList(categoryId);
        } catch (Exception e) {
            log.error("获取速回收品牌列表失败，分类ID：{}", categoryId, e);
            return new ArrayList<>();
        }
    }

    @Override
    public List<Long> getQinghuishouProductIdList(Long categoryId, Long brandId) {
        ProductQuery productQuery = new ProductQuery();
        productQuery.setCategoryId(categoryId);
        productQuery.setBrandId(brandId);
        
        List<ProductEntity> productList = productRepository.selectList(productQuery);
        
        return productList.stream()
            .map(ProductEntity::getSuProductId)
            .filter(Objects::nonNull)
            .collect(Collectors.toList());
    }

    @Override
    public SuhuishouProductListDTO getSuhuishouProductList(Long categoryId, Long brandId) {
        try {
            // 先获取品牌信息，获取速回收品牌ID
            BrandQuery brandQuery = new BrandQuery();
            brandQuery.setBrandId(brandId);
            BrandEntity brand = brandRepository.selectOne(brandQuery);
            
            if (brand == null || brand.getSuBrandId() == null) {
                log.warn("品牌{}没有对应的速回收品牌ID", brandId);
                return null;
            }
            
            return suhuishouProductApiService.requestProductList(categoryId, brand.getSuBrandId());
        } catch (Exception e) {
            log.error("获取速回收产品列表失败，分类ID：{}，品牌ID：{}", categoryId, brandId, e);
            return null;
        }
    }
    
    /**
     * 获取或创建氢回收品牌ID
     */
    private Long getOrCreateQingBrandId(SuhuishouBrandDTO suBrand) {
        // 先查询是否已存在相同名称的品牌
        BrandQuery brandQuery = new BrandQuery();
        brandQuery.setBrandName(suBrand.getBrandName());
        BrandEntity existBrand = brandRepository.selectOne(brandQuery);
        
        if (existBrand != null) {
            // 更新速回收品牌ID
            if (existBrand.getSuBrandId() == null) {
                existBrand.setSuBrandId(suBrand.getBrandId());
                existBrand.setUpdateTime(new Date());
                brandRepository.updateByPrimaryKeySelective(existBrand);
            }
            return existBrand.getBrandId();
        }
        
        // 创建新品牌
        BrandEntity newBrand = new BrandEntity();
        newBrand.setBrandName(suBrand.getBrandName());
        newBrand.setBrandImage(suBrand.getLogo());
        newBrand.setDescription("");
        newBrand.setInitial(generateInitial(suBrand.getBrandName()));
        newBrand.setSort(50);
        newBrand.setStatus(1);
        newBrand.setHandleUser("system");
        newBrand.setSuBrandId(suBrand.getBrandId());
        newBrand.setDelFlag(0);
        newBrand.setCreateTime(new Date());
        newBrand.setUpdateTime(new Date());
        
        brandRepository.insertSelective(newBrand);
        return newBrand.getBrandId();
    }
    
    /**
     * 生成首字母
     */
    private String generateInitial(String brandName) {
        if (Strings.isEmpty(brandName)) {
            return "#";
        }
        
        try {
            // 简单的首字母提取逻辑，可以根据需要完善
            char firstChar = brandName.charAt(0);
            if (Character.isLetter(firstChar)) {
                return String.valueOf(Character.toUpperCase(firstChar));
            }
            return "#";
        } catch (Exception e) {
            log.warn("生成品牌首字母失败：{}", brandName, e);
            return "#";
        }
    }
    
    /**
     * 生成关键词
     */
    private String generateKeywords(String productName) {
        if (Strings.isEmpty(productName)) {
            return "";
        }
        
        // 转换为小写并去除空格
        return productName.toLowerCase().replaceAll("\\s+", "");
    }
    
    /**
     * 获取分类名称
     */
    private String getCategoryName(Long categoryId) {
        try {
            CategoryEntity category = categoryRepository.selectByPrimaryKey(categoryId);
            if (category != null && Strings.isNotEmpty(category.getCategoryName())) {
                return category.getCategoryName();
            }
        } catch (Exception e) {
            log.warn("获取分类名称失败，分类ID: {}", categoryId, e);
        }
        return "未知分类";
    }
    
    /**
     * 获取品牌名称
     */
    private String getBrandName(Long brandId) {
        try {
            BrandEntity brand = brandRepository.selectByPrimaryKey(brandId);
            if (brand != null && Strings.isNotEmpty(brand.getBrandName())) {
                return brand.getBrandName();
            }
        } catch (Exception e) {
            log.warn("获取品牌名称失败，品牌ID: {}", brandId, e);
        }
        return "未知品牌";
    }
}
